package com.thinkgem.jeesite.modules.weixin.pageauthorization;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by yangrui on 2018/4/1.
 */
public class Sign {
    /**
     * 使用js接口时调用
     * @param ticket
     * @param url 使用js接口的页面
     * @return
     */
    public static Map<String, String> sign(JSAPITicket ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = ("jsapi_ticket=" + ticket.getTicket() + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url).toLowerCase();
        System.out.println(string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            /**
             * 对string1 字符串进行SHA-1加密处理
             */
            crypt.update(string1.getBytes("UTF-8"));
            /**
             * 对加密后字符串转成16进制
             */
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", ticket.getTicket());
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //生成随机字符串
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    //生成时间戳字符串
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
